<?php

class CommonBusi {
	/**
	 * 通过顶级父类Id取得树形数据
	 *
	 * @return Array
	 */
	static function getTree($items,$id,$idClumn,$pidClumn,$childClumn) {
		if(empty($items)) return Array();
	    $result = array();
	    foreach ($items as $row) {
	        if($row[$pidClumn] == $id){
	            $row[$childClumn] = self::getTree($items,$row[$idClumn],$idClumn,$pidClumn,$childClumn);
	            $result [] = $row;
	        }
	    }
	    return $result;
	}
	
	/**
	 * 通过父类取得子类
	 *
	 * @return Array
	 */
	static function getTreeByParent($items,$targetRow,$idClumn,$pidClumn,$childClumn) {
		if(empty($items)) return Array();
		foreach ($items as $row) {
			if($row[$pidClumn] == $targetRow[$idClumn]){
				$targetRow[$childClumn][] = self::getTreeByParent($items,$row,$idClumn,$pidClumn,$childClumn);
			}
		}
		return $targetRow;
	}
	
	/**
	 * 打包两张表的一对多数据数组结构
	 *
	 * @return Array
	 */
	static function OneToMany($items,$array,$idClumn,$childClumn) {
		if(empty($items)) return Array();
		if(empty($array)) return $items;
		foreach ($items as &$row) {
			foreach ($array as $value) {
				if($row[$idClumn] == $value[$idClumn]){
					$row[$childClumn][] = $value;
				}
			}
		}
		return $items;
	}
	
	/**
	 * 打包三张表的多对多数据数组结构
	 *
	 * @return Array
	 */
	static function ManyToMany($items,$mid,$array,$targetIdClumn,$midIdClumn,$childClumn) {
		if(empty($items)) return Array();
		if(empty($array)) return $items;
		if(empty($mid)) return $items;
		foreach ($mid as &$row) {
			foreach ($array as $value) {
				if($row[$midIdClumn] == $value[$midIdClumn]){
					$row[$childClumn] = $value;
				}
			}
		}
		foreach ($items as &$list) {
			foreach ($mid as $midList) {
				if(!empty($midList[$targetIdClumn]) && 
				!empty($midList[$childClumn]) &&
				$list[$targetIdClumn] == $midList[$targetIdClumn]){
					$list[$childClumn][] = $midList[$childClumn];
				}
			}
		}
		return $items;
	}
}

?>